﻿module Sustainalytics.Portfolio {

    import Common = Sustainalytics.Common;
    import Pager = Sustainalytics.Pager;

    // Portfolio List controller
    export class PortfolioAnalyticsController {

        public myPortfoliosList: { id: string; }[];
        public selectedFromMyPortfolios: string; 
        public allPortfoliosList: { id: string; }[];
        public selectedFromAllPortfolios: string;
        public iFrameUrl: string;
        public iFrameVisible: boolean;
        //public showGenerateButton: boolean;
        
        private userId: string;
        private accountId: string;

        // Ctor.
        constructor(
            private $rootScope: ng.IScope,
            private $scope: ng.IScope,
            private $q: ng.IQService,
            private PortfolioService: PortfolioService,
            protected $location: ng.ILocationService,
            protected $sce: ng.ISCEService,
            private $http: ng.IHttpService,
            private notificationFactory: Common.INotificationFactory) {

            var ctx = this;
            if (ctx.$rootScope['userInfo'] == null) {
                ctx.$rootScope['userInfo'] = angular.fromJson(localStorage.getItem('sust_userInfo'));
            }
            ctx.accountId = ctx.$rootScope['userInfo'].accountId;
            ctx.userId = ctx.$rootScope['userInfo'].userId;
            $scope['controller'] = ctx;

            ctx.myPortfoliosList = new Array();
            ctx.allPortfoliosList = new Array();
            ctx.iFrameVisible = false;
            ctx.initMultiSelectPortfolios();
            //ctx.showGenerateButton = true;
        }   

        private showError(err) {
            var ctx = this;
        }

        public Generate() {
            var ctx = this;
            var promise = ctx.PortfolioService.Generate(ctx.selectedFromMyPortfolios, ctx.selectedFromAllPortfolios);
            ctx.selectedFromAllPortfolios = "";
            //ctx.showGenerateButton = false;
            promise.then(response => {
                ctx.iFrameVisible = true;
                var url = response;
                var modifiedUrl = ctx.$sce.trustAsResourceUrl(url);
                ctx.iFrameUrl = modifiedUrl;
            }).catch(error => {
                //toastr.error(error);
                this.showError(error);
            });
        }

        public initMultiSelectPortfolios() {
            var ctx = this;
            var selectedFromMyPortfoliosTemp = new Array();
            var selectedFromAllPortfoliosTemp = new Array();
            var allPortfoliosTemp = new Array();
            var myPortfoliosTemp = new Array();

            //get all shared portfolios (send userId and accountId)
            var promise = ctx.PortfolioService.getMyPortfolios(ctx.userId, ctx.accountId, true, true);
            promise
                .then(data => {
                    var portfolios1: PortfolioDto[] = angular.copy(data["portfolioList"]);
                    var portfolios2: PortfolioDto[] = angular.copy(data["portfolioList"]);

                    var myPortfolios = {
                        id: "00000000-0000-0000-0000-000000000001",
                        name: "My portfolios",
                        type: 0, //custom private
                        children: new Array()
                    };
                    var sharedPortfolios = {
                        id: "00000000-0000-0000-0000-000000000003",
                        name: "Shared portfolios",
                        type: 2,
                        children: new Array()
                    };
                    myPortfoliosTemp.push(myPortfolios);
                    myPortfoliosTemp.push(sharedPortfolios);
                    portfolios1.forEach(item => {
                        var parent = myPortfoliosTemp.filter(parentItem => (parentItem.type == this.getPortfolioType(item)));
                        if (parent != null && parent[0] != null ) {
                            parent[0].children.push(item);
                        }
                    });


                    var myPortfolios2 = {
                        id: "00000000-0000-0000-0000-000000000001",
                        name: "My portfolios",
                        type: 0, //custom private
                        children: new Array()
                    };
                    var systemPortfolios2 = {
                        id: "00000000-0000-0000-0000-000000000002",
                        name: "System portfolios",
                        type: 1,
                        children: new Array()
                    };
                    var sharedPortfolios2 = {
                        id: "00000000-0000-0000-0000-000000000003",
                        name: "Shared portfolios",
                        type: 2,
                        children: new Array()
                    };
                    allPortfoliosTemp.push(myPortfolios2);
                    allPortfoliosTemp.push(systemPortfolios2);
                    allPortfoliosTemp.push(sharedPortfolios2);
                    portfolios2.forEach(item => {
                        var parent = allPortfoliosTemp.filter(parentItem => (parentItem.type == this.getPortfolioType(item)));
                        if (parent != null && parent[0] != null) {
                            parent[0].children.push(item);
                        }
                    });
                });

            // after get and count are resolved set controller properties

            var promiseAll = ctx.$q.all([promise]);
            promiseAll.then(function () {
                ctx.myPortfoliosList = myPortfoliosTemp;
                ctx.allPortfoliosList = allPortfoliosTemp;
            });
            return promiseAll;
        }

        public newSelection() {
            var ctx = this;
            //ctx.allPortfoliosList.forEach(item => item.)

        }

        public getPortfolioType(portfolio: any): number {
            if (portfolio.addedByUserId === this.userId && (!portfolio.isAutomatic)) {
                return 0;
            }

            if (portfolio.isAutomatic)
                return 1;

            return 2;
        }

            /*
          *******************************************************************
          ** Call Exago from Angular - Not used but good to have if needed **
          *******************************************************************
        public Compare(exagoApiUrl: string, exagoAppUrl: string, exagoReportName: string)
        {
            var ctx = this;
            var promiseSession: ng.IHttpPromise<{}>;
            var promiseParamenter1: ng.IHttpPromise<{}>;
            var promiseParamenter2: ng.IHttpPromise<{}>;
            var promiseReport: ng.IHttpPromise<{}>;
            var sessionId: string;
            var appUrl: string = "";
            //var promise: ng.IHttpPromise<{}> = ctx.SubscribeToPortfolioService.GetExagoReportUrlTest(exagoApiUrl, exagoReportName, ctx.selectedFromMyPortfolios, ctx.selectedFromAllPortfolios);
            var reportUrl: string = "";
            var promiseSession = this.$http({
                method: "POST",
                url: exagoApiUrl + "rest/sessions",
                withCredentials: true,
                headers: {
                    authorization: "Basic Og=="
                }
            });
            promiseSession.then(response => {
                sessionId = response.data["Id"];

                promiseParamenter1 = this.$http({
                    method: "PATCH",
                    url: exagoApiUrl + "rest/parameters/MyPortfolioId?sid=" + sessionId,
                    headers: {
                        authorization: "Basic Og=="
                    },
                    data: {
                        Value: "vlad1"
                    }
                })
                promiseParamenter1.then(response => {
                    promiseParamenter2 = this.$http({
                        method: "PATCH",
                        url: exagoApiUrl + "rest/parameters/ReferencePortfolioId?sid=" + sessionId,
                        headers: {
                            authorization: "Basic Og=="
                        },
                        data: {
                            Value: "vlad2"
                        }
                    })

                    promiseParamenter2.then(response => {
                        promiseReport = this.$http({
                            method: "PATCH",
                            url: exagoApiUrl + "rest/sessions/" + sessionId,
                            headers: {
                                authorization: "Basic Og=="
                            },
                            data: {
                                Page: "ExagoHome",
                                ApiAction: "ExecuteReport",
                                ExportType: "pdf",
                                ShowTabs: true,
                                ShowErrorDetail: true,
                                ReportSettings:
                                    { Id: null, ReportPath: exagoReportName }
                            }
                        });

                        promiseReport.then(response => {
                            reportUrl = response.data["AppUrl"];
                            ctx.iFrameVisible = true;
                            var url = exagoAppUrl + reportUrl;
                            var modifiedUrl = ctx.$sce.trustAsResourceUrl(url);
                            ctx.iFrameUrl = modifiedUrl;
                        }).catch(error => {
                            this.showError(error);
                        });
                    }).catch(err => {
                        this.showError(err)
                    });
                }).catch(err => {
                    this.showError(err)
                });
            }).catch(err => {
                this.showError(err)
                });
            
            //ctx.DisplayReport(ctx.selectedFromMyPortfolios, ctx.selectedFromAllPortfolios );
        }
        */

    }


    // register controller with News Angular module
    angular.module(portfolioModuleName).controller('PortfolioAnalyticsController',
        ['$rootScope', '$scope', '$q', 'PortfolioService', '$location', '$sce', '$http', 'notificationFactory', PortfolioAnalyticsController]);
}